//
//  IAPHelper.m
//  ProjectL
//
//  Created by Nguyen Tan Loc on 12/8/13.
//  Copyright (c) 2013 Nguyen Tan Loc. All rights reserved.
//

#import "IAPHelper.h"

@implementation IAPHelper

-(id) initWithProductIdentifiers:(NSArray *)identifiers
{
    if (self = [super init])
    {
        mListIdentifiers = [identifiers retain];
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
        
    }
    
    return self;
}

-(void) requestProductWithCompletionHandler:(RequestProductCompletionHandler)completionHandler
{
    mCompletionhandler = [completionHandler copy];
    mProductsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithArray:mListIdentifiers]];
    mProductsRequest.delegate = self;
    [mProductsRequest start];
}

-(void) productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
    CCLOG(@"load list product");
    NSArray *listProduct = response.products;
    for (SKProduct *product in listProduct)
    {
        CCLOG(@"%@ - %@ - %f", product.productIdentifier, product.localizedTitle, product.price.floatValue);
    }
    mCompletionhandler(YES, listProduct);
}

-(void) request:(SKRequest *)request didFailWithError:(NSError *)error
{
    CCLOG(@"%@", error.description);
}

-(void) paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
    CCLOG(@"paymentQueue");
    for (SKPaymentTransaction * transaction in transactions) {
        switch (transaction.transactionState)
        {
            case SKPaymentTransactionStatePurchased:
                [self completeTransaction:transaction];
                break;
            case SKPaymentTransactionStateFailed:
                [self failedTransaction:transaction];
                break;
            case SKPaymentTransactionStateRestored:
                [self restoreTransaction:transaction];
            default:
                break;
        }
    };
}

-(void) completeTransaction:(SKPaymentTransaction *) transaction
{
    CCLOG(@"completeTransaction");
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

-(void) failedTransaction:(SKPaymentTransaction *) transaction
{
    CCLOG(@"failedTransaction: %@", transaction.error.description);
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

-(void) restoreTransaction:(SKPaymentTransaction *) transaction
{
    CCLOG(@"restoreTransaction");
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

-(void) buyProduct:(NSString *)productIdentifier
{
    CCLOG(@"Buy product: %@", productIdentifier);
    SKPayment *payment = [SKPayment paymentWithProductIdentifier:productIdentifier];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}

@end
